package cn.txun.springboot61.controller;

import cn.txun.springboot61.entity.User;
import cn.txun.springboot61.entity.Weibo;
import cn.txun.springboot61.mapper.WeiboMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @RequestMapping("/weibo/insert")
    public int insert(Weibo weibo, MultipartFile picFile, HttpSession session) throws IOException {
        //从session获取当前登录对象
        User u = (User)session.getAttribute("u");
        if(u==null){//代表未登录
            return 2;//发布失败  请先登录
        }
        //获取图片的原始名称
        String filename = picFile.getOriginalFilename();
        //获取图片的后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //拿到图片的新名称
        filename = UUID.randomUUID()+suffix;
        String dirPath = "d:/upload/";
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+filename;
        picFile.transferTo(new File(filePath));

        //把微博相关信息封装到Weibo对象中
        //author,url,created,userId
        weibo.setAuthor(u.getNickname());//微博作者
        weibo.setUrl("/"+filename);//绝对路径
        weibo.setCreated(new Date());//创建日期
        weibo.setUserId(u.getId());//作者id
        weiboMapper.insert(weibo);//将微博信息保存到数据库中
        return 1;//发布成功

    }

    @RequestMapping("/weibo/select")
    public List<Weibo> select(){
        return weiboMapper.select();
    }

    @RequestMapping("/weibo/selectMyself")
    public List<Weibo> selectMyself(HttpSession session){
        User u = (User)session.getAttribute("u");
        if(u==null){//如果没有登录，返回空集合
            return new ArrayList<Weibo>();
        }
        //通过当前登录用户的id查询所有微博
        return weiboMapper.selectByUserId(u.getId());
    }

    @RequestMapping("/weibo/delete")
    public void delete(int id){
        weiboMapper.delete(id);
    }

    @RequestMapping("/weibo/selectById")
    public Weibo selectById(int id){
        return weiboMapper.selectById(id);
    }

}
